package hu.szyrt.bug.adapters;

import java.io.File;

import hu.szyrt.bug.R;
import hu.szyrt.bug.connections.DownloadPolaroidConnection;
import hu.szyrt.bug.utils.Assets;
import hu.szyrt.bug.utils.Utils;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

public class GalleryAdapter extends PagerAdapter {
	
	private Assets assets;
	private String[] names;
	public GalleryAdapter(Assets assets, String[] names) {
		this.assets = assets;
		this.names = names;
	}	
	
	
    @Override
    public void destroyItem(View collection, int position, Object o) {
        ImageView image = (ImageView)o;
        if(image != null){
        	if(image.getDrawable() != null) ((BitmapDrawable)image.getDrawable()).getBitmap().recycle();
        	((ViewPager) collection).removeView(image);
        	image = null;
        }
    }

    @Override
    public void finishUpdate(View arg0) {}
    @Override
    public int getCount() { return names.length; }
    @Override
    public Object instantiateItem(final View context, final int position) {
        final ImageView imageView = new ImageView(assets.getContext());
        imageView.setPadding(5, 0, 5, 0);
        File imageFile = Assets.getCacheFile(names[position]);
        if(imageFile.exists()){
        	imageView.setImageBitmap(BitmapFactory.decodeFile(imageFile.getAbsolutePath()));
        }else{
        	if(Utils.isInternetAvailable(assets.getContext())){
	        	final DownloadPolaroidConnection dpc = new DownloadPolaroidConnection(names[position]);
				dpc.setNotify(new DownloadPolaroidConnection.Notify(){
					public void onSuccess() {					
						imageView.setImageBitmap(assets.loadGalleryImage(dpc.getImageFile().getAbsolutePath()));
					}
					public void onError() {}
				});
				dpc.start();
        	}else{
        		Toast.makeText(assets.getContext(), R.string.err_no_internet, Toast.LENGTH_SHORT).show();
        	}
        }        
        
        ((ViewPager) context).addView(imageView);
        return imageView;
    }

    @Override
    public boolean isViewFromObject(View view, Object object) {
        return view == ((ImageView)object);
    }
    
}
